from info.modules.user import user_blu
from flask import render_template, g, abort, request, jsonify, current_app
from info.utils.common import user_login_data, upload_file
from info.utils.response_code import RET, error_map
from info.utils.models import UserCollection, Category,News
from info.utils.constants import USER_COLLECTION_MAX_NEWS,QINIU_DOMIN_PREFIX
from info import db


@user_blu.route('/user_info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        abort(403)
    return render_template("news/user.html", user=user.to_dict())


@user_blu.route('/base_info', methods=["GET", "POST"])
@user_login_data
def base_info():
    user = g.user
    if not user:
        abort(403)
    if request.method == "GET":  # 展示页面
        return render_template("news/user_base_info.html", user=user.to_dict())

    # Post 提交数据

    # 获取参数
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")

    # 校验参数
    if not all([signature, gender, nick_name]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 修改用户信息
    user.gender = gender
    user.nick_name = nick_name
    user.signature = signature

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


@user_blu.route('/pic_info', methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if not user:
        abort(403)
    if request.method == "GET":  # 展示页面
        return render_template("news/user_pic_info.html", user=user.to_dict())

    # Post 提交数据

    # 获取参数
    avatar_file = request.files.get("avatar")

    # 校验参数
    try:
        img_bytes = avatar_file.read()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 　上传头像
    try:
        avatar_url = upload_file(img_bytes)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])

    # 修改头像的地址
    user.avatar_url = avatar_url

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=user.to_dict())


@user_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    user = g.user
    if not user:
        abort(403)
    if request.method == "GET":  # 展示页面
        return render_template("news/user_pass_info.html", user=user.to_dict())

    # Post 提交数据

    # 获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 校验参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if not user.check_passoword(old_password):
        return jsonify(errno=RET.PWDERR, errmsg=error_map[RET.PWDERR])

    # 修改用户信息
    user.password = new_password

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


@user_blu.route('/collection', methods=["GET", "POST"])
@user_login_data
def collection():
    user = g.user
    if not user:
        abort(403)
    if request.method == "GET":  # 展示页面
        p = request.args.get("p", 1)
        try:
            p = int(p)
        except BaseException as e:
            current_app.logger.error(e)
            return abort(403)

        try:
            pn = user.collection_news.order_by(UserCollection.create_time.desc()).paginate(p, USER_COLLECTION_MAX_NEWS)
        except BaseException as e:
            current_app.logger.error(e)
            return abort(500)
        data = {
            "news_list": [news.to_dict() for news in pn.items],
            "total_page": pn.pages,
            "cur_page": pn.page
        }

        return render_template("news/user_collection.html", user=user.to_dict(), data=data)


# 发布新闻页面
@user_blu.route('/news_release', methods=["GET", "POST"])
@user_login_data
def news_release():
    user = g.user
    if not user:
        abort(403)
    if request.method == "GET":  # 展示页面
        try:
            categories = Category.query.filter(Category.id != 1).all()
        except BaseException as e:
            current_app.logger.error(e)
            return abort(500)
        return render_template("news/user_news_release.html", categories=categories)

    # Post 提交数据

    # 获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image_file = request.files.get("index_image")
    content = request.form.get("content")

    # 校验参数
    if not all([title, category_id, digest, content, index_image_file]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    try:
        category_id = int(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 数据库行为: 生成一条新闻纪录
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    # 上传图片
    try:
        img_bytes = index_image_file.read()
        file_name = upload_file(img_bytes)
        news.index_image_url = QINIU_DOMIN_PREFIX + file_name
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])

    # 设置其他字段
    news.source = "个人发布"  # 发布来源
    news.user_id = user.id  # 作者id
    news.status = 1  # 设置新闻状态  1表示待审核

    # 添加到会话
    db.session.add(news)

    # json返回结果
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])

# 实现新闻发布页面
@user_blu.route('/news_list', methods=["GET", "POST"])
@user_login_data
def news_list():
    user = g.user
    if not user:
        abort(403)
    if request.method == "GET":  # 展示页面
        p = request.args.get("p", 1)
        try:
            p = int(p)
        except BaseException as e:
            current_app.logger.error(e)
            return abort(403)

        try:
            pn = user.news_list.paginate(p,USER_COLLECTION_MAX_NEWS)
        except BaseException as e:
            current_app.logger.error(e)
            return abort(500)
        data = {
            "news_list": [news.to_review_dict() for news in pn.items],
            "total_page": pn.pages,
            "cur_page": pn.page
        }

        return render_template("news/user_news_list.html", data=data)


# 实现我关注的人
@user_blu.route('/user_follow', methods=["GET", "POST"])
@user_login_data
def user_follow():
    user = g.user
    if not user:
        abort(403)
    if request.method == "GET":  # 展示页面
        p = request.args.get("p", 1)
        try:
            p = int(p)
        except BaseException as e:
            current_app.logger.error(e)
            return abort(403)

        try:
            pn = user.followed.paginate(p,USER_COLLECTION_MAX_NEWS)
        except BaseException as e:
            current_app.logger.error(e)
            return abort(500)
        data = {
            "author_list": [author.to_dict() for author in pn.items],
            "total_page": pn.pages,
            "cur_page": pn.page
        }

        return render_template("news/user_follow.html", data=data)